package com.example.androidreviewapp

import android.content.ComponentName
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import com.example.androidreviewapp.model.RunAppInfo
import com.google.gson.reflect.TypeToken
import com.shaoman.customer.helper.DataSaveImpl
import com.shenghuai.bclient.stores.adapter.ListSimpleAdapter
import com.shenghuai.bclient.stores.common.OnDestroyLifeObserver
import com.shenghuai.bclient.stores.util.SafeUtils
import kotlinx.coroutines.*

/**
 * 获取手机里面的需要的程序图标
 */
class RunAppInfosAddHelper {

    private val runAppInfos = mutableListOf<RunAppInfo>()
    private val packagegMgr: PackageManager
    private var startActivityFunc: Function1<Intent, Unit>? = null

    @Suppress("ConvertSecondaryConstructorToPrimary")
    constructor(context: AppCompatActivity) {
        packagegMgr = context.packageManager
        startActivityFunc = { intent ->
            context.startActivity(intent)
        }
        context.lifecycle.addObserver(OnDestroyLifeObserver {
            runAppInfos.clear()
            startActivityFunc = null
        })
    }

    fun build(adapter: ListSimpleAdapter<RunAppInfo>) {
        runAppInfos.clear()

        MainScope().launch {

            val ret = async {
                var ret = 1
                val cacheRunAppInfos = fetchCacheRunAppInfos()
                if (cacheRunAppInfos.isNotEmpty()) {
                    println("xxxx obtain cacheRunAppInfos successfully")
                    runAppInfos.addAll(cacheRunAppInfos)
                } else {
                    createSomeItems()
                    ret = 2
                }
                ret
            }
            val count = ret.await()

            if (runAppInfos.isNotEmpty()) {
                adapter.insertItems(runAppInfos)
            }
            if (count == 2) {
                // 保存runAppInfos到sdcard
                CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {
                    val jsonString = DataSaveImpl.getGson().toJson(runAppInfos)
                    DataSaveImpl.save("runAppInfos", jsonString)
                }
            }
        }
    }

    private fun fetchCacheRunAppInfos(): MutableList<RunAppInfo> {
        var jsonStr = DataSaveImpl.get("runAppInfos", String::class.java) as? String ?: "[]"
        //mutableListOf<RunAppInfo>()
        if (jsonStr.isEmpty()) {
            jsonStr = "[]"
        }
        @Suppress("UNCHECKED_CAST")
        val typeToken: TypeToken<MutableList<RunAppInfo>> =
            TypeToken.getParameterized(
                MutableList::class.java,
                RunAppInfo::class.java
            ) as TypeToken<MutableList<RunAppInfo>>
        return DataSaveImpl.getGson().fromJson(jsonStr, typeToken.type)
    }

    private fun createSomeItems() {

        RunAppInfo("微信", "com.tencent.mm").addSelf(runAppInfos)
        RunAppInfo("QQ", "com.tencent.mobileqq").addSelf(runAppInfos)
        RunAppInfo("米家", "com.xiaomi.smarthome").addSelf(runAppInfos)
        RunAppInfo("向日葵远程控制", "com.oray.sunlogin").addSelf(runAppInfos)
        RunAppInfo("支付宝", "com.eg.android.AlipayGphone").addSelf(runAppInfos)
        RunAppInfo("拼多多", "com.xunmeng.pinduoduo").addSelf(runAppInfos)
        RunAppInfo("MT管理器", "bin.mt.plus").addSelf(runAppInfos)
        RunAppInfo("文件闪传", "app.eleven.com.fastfiletransfer").addSelf(runAppInfos)
        RunAppInfo("BOSS直聘", "com.hpbr.bosszhipin").addSelf(runAppInfos)

        // com.tencent.mm/.plugin.scanner.ui.BaseScanUI

        RunAppInfo("微信扫一扫", "com.tencent.mm").setLoadTask {
            val intent = Intent(Intent.ACTION_VIEW)
            intent.component =
                ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI")
            intent.putExtra("LauncherUI.From.Scaner.Shortcut", true)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
            safeStartActivity(intent)
        }
            .setIconRes(R.mipmap.wechat_query)
            .setActivityComponentName(
                ComponentName(
                    "com.tencent.mm",
                    "com.tencent.mm.plugin.scanner.ui.BaseScanUI"
                )
            ).addSelf(runAppInfos)


        RunAppInfo("支付宝扫一扫", "com.eg.android.AlipayGphone")
            .setIconRes(R.mipmap.qq_query)
            .setLoadTask {
                val uri: Uri = Uri.parse("alipayqr://platformapi/startapp?saId=10000007")
                val intent = Intent(Intent.ACTION_VIEW, uri)
                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
                safeStartActivity(intent)
            }
            .addSelf(runAppInfos)

        val settingsComponentName =
            ComponentName("com.android.settings", "com.android.settings.Settings")

        RunAppInfo("设置", "com.android.settings", true)
            .setComponentName(settingsComponentName)


        RunAppInfo("相册", "com.android.gallery3d")
            .setLoadTask {
                openGallery()
            }.addSelf(runAppInfos)

        RunAppInfo("高德地图", "com.autonavi.minimap").addSelf(runAppInfos)
        RunAppInfo("企业微信", "com.tencent.wework").addSelf(runAppInfos)
        RunAppInfo("adbWifi", "com.ttxapps.wifiadb").addSelf(runAppInfos)
        RunAppInfo("稍曼社区", "com.shaoman.customer").addSelf(runAppInfos)
        RunAppInfo("应用宝", "com.tencent.android.qqdownloader").addSelf(runAppInfos)
        RunAppInfo("PandaVpn", "com.pandavpn.androidproxy").addSelf(runAppInfos)
        RunAppInfo("SSH Server", "net.xnano.android.sshserver").addSelf(runAppInfos)
        RunAppInfo("YouTube", "com.google.android.youtube").addSelf(runAppInfos)
        RunAppInfo("Google Play", "com.android.vending").addSelf(runAppInfos)
        RunAppInfo("京东极速版", "com.jd.jdlite").addSelf(runAppInfos)
    }

    /**
     * 安全启动activity捕获异常
     */
    private fun safeStartActivity(intent: Intent) {
        SafeUtils.safeRun {
            startActivity(intent)
        }
    }

    /**
     * 打开系统相册
     */
    private fun openGallery() {
        val packageName = arrayOf(
            "com.android.gallery3d",
            "com.miui.gallery"
        )
        for (pack in packageName) {
            val launcherIntent = packagegMgr.getLaunchIntentForPackage(pack)
            if (launcherIntent != null && packagegMgr.resolveActivity(
                    launcherIntent, PackageManager.MATCH_ALL
                ) != null
            ) {
                startActivity(launcherIntent)
                break
            }
        }
    }

    private fun startActivity(intent: Intent) {
        startActivityFunc?.invoke(intent)
    }

    /**
     * 获取activity的图标
     */
    private fun setActivityIcon(imageView: ImageView, componentName: ComponentName?) {
        if (componentName == null) return

        SafeUtils.safeRun {
            val activityIcon = packagegMgr.getActivityIcon(componentName)
            imageView.setImageDrawable(activityIcon)
        }
    }

    /**
     * 刷新噢
     */
    fun refresh(adapter: ListSimpleAdapter<RunAppInfo>) {
        MainScope().launch {
            val ret = async {
                runAppInfos.clear()
                createSomeItems()
                val ret = 2
                ret
            }
            val count = ret.await()

            if (runAppInfos.isNotEmpty()) {
                adapter.removeAll()
                adapter.insertItems(runAppInfos)
            }
            if (count == 2) {
                // 保存runAppInfos到sdcard
                CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {
                    val jsonString = DataSaveImpl.getGson().toJson(runAppInfos)
                    DataSaveImpl.save("runAppInfos", jsonString)
                }
            }
        }
    }


}